/**
 * 路由拦截器
 * Created by wdb
 */
var sysConfig       = require('./config');
var utils           = require("./utils");
var DataProxy       = require("data-proxy");
var async           = require('async');
var Action          = require("./routes/apiaction");
var https           = require('https');
var expiredTime     = 900000000;
var webdebug        = true;
//var t=1;
exports.filterFun = function (req, res, next) {
    //clearCookies(req, res, next);
    console.log("***************开始******************")
    //白名单校验
    var url = req.originalUrl;
    console.log(url);
    var boo = sysConfig.isWhiteList(url);
    if(boo) {
        return next();
    } else {
        console.log("*******************拦截************************");
        clientFun(req, res,next);
    }

}

var clearCookies = function(req, res, next){
    res.clearCookie('sessionid', { path: '/wap' });
    res.clearCookie('username', { path: '/wap' });
    res.clearCookie('userid', { path: '/wap' });
    res.clearCookie('role', { path: '/wap' });
    req.cookies.sessionid = undefined;
    req.cookies.username = undefined;
    req.cookies.userid = undefined;
    req.cookies.role = undefined;

}
//PC
var clientPc = function(req, res, next) {
    var url         = req.originalUrl;
    var oldurl      = url;
    var sessionid   = req.cookies.sessionid;
    var boo         = false,//标记是否需要登录,false=不需要登录，true=要登录
        login       = "",

    boo     = sysConfig.isPcAuthor(url);
    login   = "/login?tourl=" + oldurl;

    if (boo) {//需要登录
        if(!sessionid) {
            res.redirect('/login');
        }else {
            Action.send(req, res,"check",{sessionid:sessionid},function(res,data){
                var json = JSON.parse(data);
                if(json.code == 1 ){
                    res.redirect('/login');
                }else {
                    return next();
                }
            });
        }
    }else {
        return next();
    }
}
//Mobile
var clientWap = function(req, res, next) {
    nextWx(req,res,next);
}



var clientFun = function(req, res, next) {

    var url     = req.originalUrl;
    var referer = req.headers.referer;
    console.log("    ====clientFun=======",url,referer);
    //if(url.indexOf("/api/") != -1 || url.indexOf("/callback") != -1 || url.indexOf("/wxnotify/") != -1||url.indexOf('/alipayto')!=-1||url.indexOf('/return')!=-1||url.indexOf('/notify')!=-1) {//调用接口
    if(url.indexOf("/api/") != -1 || url.indexOf("/js/biz") != -1||url.indexOf("/upload")!=-1 ) {//调用接口
        return next();
    } else if(url.indexOf("/wap") == -1) {//PC
        console.log("[[[PC]]]");
        clientPc(req, res, next);
    }
}
